package com.service.business.trading.controller;

import com.service.business.base.dto.LoginUserSession;
import com.service.business.framework.log.RequestLog;
import com.service.business.member.service.MemberStoreService;
import com.service.business.support.MemberStoreLockUtils;
import com.service.business.support.SessionUtil;
import com.service.business.support.TradingSpotLockUtils;
import com.service.business.trading.controller.rep.TradingSpotConfigRep;
import com.service.business.trading.controller.rep.TradingSpotOrderPageRep;
import com.service.business.trading.controller.rep.TradingSpotTradeRep;
import com.service.business.trading.controller.req.TradingSpotCreateReq;
import com.service.business.trading.controller.req.TradingSpotPageReq;
import com.service.business.trading.service.TradingSpotOrderService;
import com.service.business.trading.service.TradingSpotPairsService;
import com.service.business.trading.service.TradingSpotTradesService;
import com.service.core.exception.CommonException;
import com.service.core.rest.BaseController;
import com.service.core.rest.request.PageRequest;
import com.service.core.rest.response.BaseResponse;
import com.service.core.rest.response.OneResponse;
import com.service.core.rest.response.PageResponse;
import com.service.dao.model.MemberStore;
import com.service.dao.model.TradingSpotPairs;
import com.service.match.common.enums.TradingSpotEnum;
import com.service.match.common.utils.TradingSpotUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("trading-spot")
public class TradingSpotController extends BaseController {

    @Autowired
    private SessionUtil sessionUtil;
    @Autowired
    private MemberStoreLockUtils storeLockUtils;
    @Autowired
    private MemberStoreService memberStoreService;
    @Autowired
    private TradingSpotTradesService spotTradesService;
    @Autowired
    private TradingSpotOrderService tradingSpotOrderService;
    @Autowired
    private TradingSpotPairsService tradingSpotPairsService;

    @RequestLog("币币交易配置")
    @GetMapping("list-pairs-config")
    public OneResponse<TradingSpotConfigRep> listPairsConfig() {
        return successQueryOneResponse(tradingSpotOrderService.listPairsConfig());
    }

    @RequestLog("创建币币交易买单")
    @PostMapping("create/buy-order")
    public BaseResponse createBuyOrder(@RequestBody @Validated TradingSpotCreateReq createReq) {
        return createOrder(createReq, TradingSpotEnum.TradeType.BUY);
    }

    @RequestLog("创建币币交易卖单")
    @PostMapping("create/sell-order")
    public BaseResponse createSellOrder(@RequestBody @Validated TradingSpotCreateReq createReq) {
        return createOrder(createReq, TradingSpotEnum.TradeType.SELL);
    }


    private BaseResponse createOrder(TradingSpotCreateReq createReq, TradingSpotEnum.TradeType tradeType) {
        LoginUserSession session = sessionUtil.getUser();
        if(session.getStoreFreezeStatus() == com.service.dao.enums.MemberEnums.StoreStatus.FROZEN.getCode()){
            throw new CommonException("账户资产已冻结，如有疑问请联系客服","account_assets_frozen");
        }
        TradingSpotPairs spotPairs = tradingSpotPairsService.getBySymbol(createReq.getSymbol());
        if (ObjectUtils.isEmpty(spotPairs)) {
            throw new CommonException("不存在此交易对", "trading_spot_exception_symbol_not_exist");
        }
        String lockCoinName = "";
        if (TradingSpotUtils.isBuy(tradeType.getCode())) {
            lockCoinName = spotPairs.getTradeCoinsName();
        } else {
            lockCoinName = spotPairs.getCoinsName();
        }
        MemberStore memberStore = memberStoreService.getMemberStore(session.getUserId(), lockCoinName);
        if(storeLockUtils.lock(session.getUserId(), memberStore.getId())){
            try {
                tradingSpotOrderService.createOrder(createReq, tradeType, session, spotPairs);
            } finally {
                storeLockUtils.unlock(session.getUserId(), memberStore.getId());
            }
        }
        return successBaseResponse();
    }

    @RequestLog("币币交易分页查询")
    @PostMapping("page")
    public PageResponse<TradingSpotOrderPageRep> listTradingOrder(@RequestBody TradingSpotPageReq pageReq) {
        return successQueryPageResponse(tradingSpotOrderService.pageSpot(pageReq));
    }

    @RequestLog("币币交易分页查询")
    @PostMapping("page-trades/{orderNo}")
    public PageResponse<TradingSpotTradeRep> listOrderTrade(@PathVariable("orderNo") String orderNo, PageRequest pageRequest) {
        return successQueryPageResponse(spotTradesService.pageSpotTrades(orderNo, pageRequest));
    }

    @RequestLog("申请撤消币币交易")
    @PostMapping("apply-cancel/{tradeNo}")
    public BaseResponse applyCancelOrder(@PathVariable("tradeNo") String tradeNo) {
        tradingSpotOrderService.applyCancelSpotOrder(tradeNo);
        return successBaseResponse();
    }

}
